<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="药品名称" prop="drugsName">
        <el-input
          v-model="queryParams.drugsName"
          placeholder="请输入药品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="drugsKeyword">
        <el-input
          v-model="queryParams.drugsKeyword"
          placeholder="请输入关键字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品类型" prop="drugsType">
        <el-select v-model="queryParams.drugsType" placeholder="药品类型" clearable size="small">
          <el-option
            v-for="dict in drugsTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产厂家" prop="drugsManufactor">
        <el-select v-model="queryParams.drugsManufactor" placeholder="生产厂家" clearable size="small">
          <el-option
            v-for="dict in manufactorlist"
            :key="dict.manufactorId"
            :label="dict.manufactorName"
            :value="dict.manufactorId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处方类型" prop="drugsPrescription">
        <el-select v-model="queryParams.drugsPrescription" placeholder="处方类型" clearable size="small">
          <el-option
            v-for="dict in drugsPrescriptionOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="药品状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:drugs:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:drugs:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:drugs:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
       <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['his:drugs:import']"
        >导入删除药品
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drugsList" @selection-change="handleSelectionChange" @cell-dblclick="dblclickEdit">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="药品ID" align="center" prop="drugsId"/>
      <el-table-column label="药品名称" align="center" prop="drugsName"/>
      <el-table-column label="药品编码" align="center" prop="drugsCode"/>
      <el-table-column label="生产厂家" align="center" prop="drugsManufactor" :formatter="drugsManufactorFormat"/>
      <el-table-column label="药品类型" align="center" prop="drugsType" :formatter="drugsTypeFormat"/>
      <el-table-column label="处方类型" align="center" prop="drugsPrescription" :formatter="drugsPrescriptionFormat"/>
      <el-table-column label="单位" align="center" prop="drugsCompany" :formatter="drugsCompanyFormat"/>
      <el-table-column label="处方价格" align="center" prop="drugsPrice"/>
      <el-table-column label="库存量" align="center" prop="drugsStock"/>
      <el-table-column label="预警值" align="center" prop="drugsWarning"/>
      <el-table-column label="换算量" align="center" prop="drugsConversion"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:drugs:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:drugs:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品信息对话框 -->
    <el-dialog :title="title" center :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品名称" prop="drugsName">
              <el-input v-model="form.drugsName" placeholder="请输入药品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品编码" prop="drugsCode">
              <el-input v-model="form.drugsCode" placeholder="请输入药品编码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字" prop="drugsKeyword">
              <el-input v-model="form.drugsKeyword" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="drugsCompany">
              <el-select v-model="form.drugsCompany" placeholder="请选择单位">
                <el-option
                  v-for="dict in drugsCompanyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="换算量" prop="drugsConversion">
              <el-input maxlength="1" v-model.number="form.drugsConversion" placeholder="请输入换算量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处方价格" prop="drugsPrice">
              <el-input-number v-model="form.drugsPrice" placeholder="请输入处方价格"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="库存量" prop="drugsStock">
              <el-input v-model.number="form.drugsStock" placeholder="请输入库存量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警值" prop="drugsWarning">
              <el-input-number v-model="form.drugsWarning" placeholder="请输入预警值"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品类型" prop="drugsType">
              <el-select v-model="form.drugsType" placeholder="请选择药品类型">
                <el-option
                  v-for="dict in drugsTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处方类型" prop="drugsPrescription">
              <el-select v-model="form.drugsPrescription" placeholder="请选择处方类型">
                <el-option
                  v-for="dict in drugsPrescriptionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="drugsManufactor">
              <el-select v-model="form.drugsManufactor" placeholder="请选择生产厂家">
                <el-option
                  v-for="dict in manufactorlist"
                  :key="dict.manufactorId"
                  :label="dict.manufactorName"
                  :value="dict.manufactorId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDrugs, getDrugs, delDrugs, addDrugs, updateDrugs,drugsManufactorList,importTemplate } from '@/api/his/drugs'
  import { getToken } from "@/utils/auth";
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'Drugs',
    components: { Treeselect },
    data() {
      return {
        manufactorlist:'',
        //枚举方法存放函数
        drugsTypeOptions: '',
        drugsPrescriptionOptions: '',
        drugsCompanyOptions: '',
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 药品费用表格数据
        drugsList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 类别数据字典
        categoryOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          drugsName: undefined,
          drugsManufactor: undefined,
          drugsCode: undefined,
          drugsType: undefined,
          drugsPrescription: undefined,
          drugsCompany: undefined,
          drugsPrice: undefined,
          drugsStock: undefined,
          drugsWarning: undefined,
          drugsConversion: undefined,
          createTime: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          drugsName: [
            { required: true, message: '药品名称不能为空', trigger: 'blur' }
          ],
          drugsKeyword: [
            { required: true, message: '关键字不能为空', trigger: 'blur' }
          ],
          drugsConversion: [
            { required: true, message: '关键字不能为空', trigger: 'blur' },
          ],
        },

        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/his/drugs/importData"
        },
      }
    },
    created() {
      this.getList()
      this.getDicts('sys_normal_disable').then(response => {
        this.statusOptions = response.data
      })
      this.getDicts('dms_drugs_type').then(response => {
        this.drugsTypeOptions = response.data
      })
      this.getDicts('dms_drugs_prescription').then(response => {
        this.drugsPrescriptionOptions = response.data
      })
      this.getDicts('dms_drugs_company').then(response => {
        this.drugsCompanyOptions = response.data
      })
    },
    methods: {

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },

      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },

      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },

      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },

      // 单位字典翻译
      drugsCompanyFormat(row, column) {
        return this.selectDictLabel(this.drugsCompanyOptions, row.drugsCompany)
      },
      // 处方类型字典翻译
      drugsTypeFormat(row, column) {
        return this.selectDictLabel(this.drugsTypeOptions, row.drugsType)
      },
      // 处方类型字典翻译
      drugsPrescriptionFormat(row, column) {
        return this.selectDictLabel(this.drugsPrescriptionOptions, row.drugsPrescription)
      },

      // 药品厂家格式化
      drugsManufactorFormat(row, column) {
        var actions = [];
        Object.keys(this.manufactorlist).some((key) => {
          if (this.manufactorlist[key].manufactorId == ('' + row.drugsManufactor)) {
            actions.push(this.manufactorlist[key].manufactorName);
            return true;
          }
        })
        return actions.join('');
      },

      /*双击修改*/
      dblclickEdit(row, column, cell, event){
        this.handleUpdate(row)
      },

      /** 查询药品信息列表 */
      getList() {
        this.loading = true
        drugsManufactorList().then(response =>{
          let j
          for (j = 0 ;j <response.length;j++){
            response[j].manufactorId = response[j].manufactorId.toString()
          }
          this.manufactorlist = response
        })
        listDrugs(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
          this.drugsList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 字典状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status)
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          drugsConversion : 1,
          drugsPrice: 0,
          status : '0'
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.drugsId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加药品信息'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const drugsId = row.drugsId || this.ids
        getDrugs(drugsId).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改药品信息'
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.drugsId != undefined) {
              updateDrugs(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addDrugs(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const drugsIds = row.drugsId || this.ids
        this.$confirm('是否确认删除药品编号为"' + drugsIds + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delDrugs(drugsIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(() => {
        })
      }
    }
  }
</script>
